package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.WXPAY;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.app.MyAppliaction;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.AnyOrderBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.WechatinfoBean;
import com.luoxiang.socialandroid.bean.ZhifuBaoBean;
import com.luoxiang.socialandroid.common.PayResult;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ChargeActivity extends BaseActivity {
    private int id;
    private ImageView icon_back, im_charge, im_zfb, im_wx, im_bc;
    private TextView tx_yxq, tx1_charge, tx_price;
    private Button bt_charge;
    private RelativeLayout re_zfb, re_wx, re_bc;
    private Boolean zfb = true, wx, bc;
    private int payment = 0;
    private String details;
    private String icon;
    private String name;
    private double amount;
    private String token;
    private String order;
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtils.showShort(R.string.mi_zhifuchenggong);
                        finish();
                    } else {
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtils.showShort(R.string.mi_zhifujieguoquerenzhong);
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            ToastUtils.showShort(R.string.mi_zhifuquxiao);
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                            ToastUtils.showShort(R.string.mi_wangluoyichang);
                        } else if (TextUtils.equals(resultStatus, "5000")) {
                            ToastUtils.showShort(R.string.mi_qingqiuchongfu);
                        } else {
                            // 其他值就可以判断为支付失败
                            ToastUtils.showShort(R.string.mi_zhifushibai);
                            finish();
                        }
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected void initListener() {
        re_zfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                zfb = true;
                payment = 1;
                wx = false;
                bc = false;
                im_zfb.setImageResource(R.mipmap.yijinggouxuan);
                im_wx.setImageResource(R.mipmap.icon_czweigouxuan);
                im_bc.setImageResource(R.mipmap.icon_czweigouxuan);
            }
        });
        re_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                zfb = false;
                payment = 0;
                wx = true;
                bc = false;
                im_zfb.setImageResource(R.mipmap.icon_czweigouxuan);
                im_wx.setImageResource(R.mipmap.yijinggouxuan);
                im_bc.setImageResource(R.mipmap.icon_czweigouxuan);
            }
        });
        re_bc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                zfb = false;
                wx = false;
                bc = true;
                payment = 2;
                im_zfb.setImageResource(R.mipmap.icon_czweigouxuan);
                im_wx.setImageResource(R.mipmap.icon_czweigouxuan);
                im_bc.setImageResource(R.mipmap.yijinggouxuan);
            }
        });
        bt_charge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (zfb) {
                    buyvip(token, EXTRA, 1, id);
                } else if (wx) {
                    buyvip(token, EXTRA, 0, id);
                } else if (bc) {
                    ToastUtils.showShort(R.string.mi_zanweikaitongfuwu);
                }
            }
        });
        icon_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void buyvip(String token, String extra, int i, int id) {
        NetUtils.getInstance().getApiService().buyVip(extra, token, i, id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr200", decryptStr);
                        Gson gson1 = new Gson();
                        AnyOrderBean anyOrderBean = gson1.fromJson(decryptStr, AnyOrderBean.class);
                        int payPattern = anyOrderBean.getData().getPayPattern();
                        switch (payment) {
                            case 0:
                                if (payPattern == 0){
                                    Gson gson = new Gson();
                                    WechatinfoBean bean = gson.fromJson(decryptStr, WechatinfoBean.class);
                                    IWXAPI api = WXAPIFactory.createWXAPI(ChargeActivity.this, bean.getData().getOrder().getAppid());
                                    api.registerApp(bean.getData().getOrder().getAppid());
                                    PayReq payReq = new PayReq();
                                    payReq.appId = bean.getData().getOrder().getAppid();
                                    payReq.partnerId = bean.getData().getOrder().getPartnerid();
                                    payReq.prepayId = bean.getData().getOrder().getPrepayid();
                                    payReq.packageValue = bean.getData().getOrder().getPackage();
                                    payReq.nonceStr = bean.getData().getOrder().getNoncestr();
                                    payReq.timeStamp = bean.getData().getOrder().getTimestamp();
                                    payReq.sign = bean.getData().getOrder().getSign();
                                    boolean b = api.sendReq(payReq);
                                    LogUtils.i("boolean", b);
                                }else{
                                    ZhifuBaoBean zhifuBaoBean = gson1.fromJson(decryptStr,ZhifuBaoBean.class);
                                    if (zhifuBaoBean != null) {
                                        if (zhifuBaoBean.getData() != null) {
                                            if (zhifuBaoBean.getData().getOrder() != null) {
                                                order = zhifuBaoBean.getData().getOrder();//订单信息
                                            }
                                        }
                                    }
                                    Intent intent = new Intent(ChargeActivity.this, WebContentActivity.class);
                                    String s = order.replaceAll("\u003d", "=").replaceAll("\u0026", "&");
                                    LogUtils.i("ssssdd", s);
                                    intent.putExtra("h5url", s);
                                    startActivity(intent);
                                }
                                break;
                            case 1:
                                ZhifuBaoBean zhifuBaoBean = gson1.fromJson(decryptStr, ZhifuBaoBean.class);
                                if (zhifuBaoBean != null) {
                                    if (zhifuBaoBean.getData() != null) {
                                        if (zhifuBaoBean.getData().getOrder() != null) {
                                            order = zhifuBaoBean.getData().getOrder();//订单信息
                                        }
                                    }
                                }
                                if (payPattern == 0){
                                    Runnable payRunnable = () -> {
                                        PayTask alipay = new PayTask(ChargeActivity.this);
                                        Map<String, String> result = alipay.payV2(order, true);
                                        Message msg = new Message();
                                        msg.what = SDK_PAY_FLAG;
                                        msg.obj = result;
                                        mHandler.sendMessage(msg);
                                    };
                                    // 必须异步调用
                                    Thread payThread = new Thread(payRunnable);
                                    payThread.start();
                                }else{
                                    Intent intent = new Intent(ChargeActivity.this, WebContentActivity.class);
                                    String s = order.replaceAll("\u003d", "=").replaceAll("\u0026", "&");
                                    LogUtils.i("ssssdd", s);
                                    intent.putExtra("h5url", s);
                                    startActivity(intent);
                                }
                                break;
                            case 2:

                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {}

                    @Override
                    public void onComplete() {}
                });
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_charge);
//        setStatusBarTranslucent();
        UltimateBarX.statusBarOnly(this).transparent().light(false).apply();
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        details = intent.getStringExtra("details");
        icon = intent.getStringExtra("icon");
        name = intent.getStringExtra("name");
        int validMonth = intent.getIntExtra("ValidMonth", -1);
        amount = intent.getDoubleExtra("amount", 0);
        id = intent.getIntExtra("id", 0);
        im_charge = findViewById(R.id.im_charge);
        icon_back = findViewById(R.id.icon_back);
        tx_yxq = findViewById(R.id.tx_yxq);
        tx1_charge = findViewById(R.id.tx1_charge);
        tx_price = findViewById(R.id.tx_price);
        bt_charge = findViewById(R.id.bt_charge);
        re_zfb = findViewById(R.id.re_zfb);
        re_wx = findViewById(R.id.re_wx);
        re_bc = findViewById(R.id.re_bc);
        im_zfb = findViewById(R.id.im_zfb);
        im_wx = findViewById(R.id.im_wx);
        im_bc = findViewById(R.id.im_bc);
        im_zfb.setImageResource(R.mipmap.yijinggouxuan);
        Glide.with(MyAppliaction.getContext())
                .load("https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/" + icon)
                .into(im_charge);
        if (validMonth > 3) {
            tx_yxq.setText(R.string.mi_youxiaoqizhongsheng);
        } else {
            tx_yxq.setText(getString(R.string.mi_youxiaoqi) + validMonth + getString(R.string.mi_geyue));
        }
        tx1_charge.setText(getString(R.string.mi_kaitong) + name);
        tx_price.setText("￥" + (int) amount);
        bt_charge.setText("￥" + (int) amount + getString(R.string.mi_lijizhifu));
        Integer wxpay = MmkvUtil.INSTANCE.decodeInt(WXPAY);
        if (wxpay == 0) {
            re_wx.setVisibility(View.GONE);
        } else {
            re_wx.setVisibility(View.VISIBLE);

        }

    }
}
